<script setup lang="ts">
import XtxGuess from '@/components/XtxGuess.vue'
import { useGuessList } from '@/composables'
import type { ICartItem } from '@/types/cart'
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import Api from '@/services'
import type { InputNumberBoxEvent } from '@/components/vk-data-input-number-box/vk-data-input-number-box'
import { useMemberStore } from '@/stores'
import CartSkeleton from './CartSkeleton.vue'

// 猜你喜欢-组合式函数
const { xtxguessRef, onScrollToLower } = useGuessList()
const cartList = ref<ICartItem[]>()
const loading = ref(true)

const options: UniHelper.UniSwipeActionItemOption[] = [
  {
    text: '删除',
    style: {
      backgroundColor: 'red',
      color: '#fff',
      fontSize: '26rpx',
    },
  },
]

const profile = computed(() => {
  return useMemberStore().profile
})
// const selectAll = ref(false)

const selectedLength = computed(() => {
  return cartList.value?.filter((item) => item.selected).length
})

const totalPrice = computed(() => {
  return cartList.value?.reduce((a, b) => a + (b.selected ? b.price * b.count : 0), 0)
})

const selectAll = computed(() => {
  return cartList.value?.length && cartList.value?.every((item) => item.selected)
})

const getCartList = async () => {
  const { result: data } = await Api.CartAPI.getCartList()
  cartList.value = data
}
onLoad(async () => {
  loading.value = true
  await getCartList()
  loading.value = false
})

const onChangeCount = async (ev: InputNumberBoxEvent) => {
  await Api.CartAPI.updateCartItem({ skuId: ev.index, count: ev.value })
}

const onChangeSelect = async (item: ICartItem) => {
  item.selected = !item.selected
  console.log(item, 'item')
  await Api.CartAPI.updateCartItem({
    skuId: item.skuId,
    selected: item.selected,
  })
}

const onChangeAll = async () => {
  const _selectedAll = !selectAll.value
  cartList.value?.forEach((item) => {
    item.selected = _selectedAll
  })
  await Api.CartAPI.updateAllSelected(_selectedAll)
}

const deleteCart = async (id: string) => {
  await Api.CartAPI.deleteCartItem([id])
  await getCartList()
}

const toPre = () => {
  uni.navigateTo({
    url: '/pagesOrder/orderPre/orderPre',
  })
}
</script>

<template>
  <CartSkeleton v-if="loading"></CartSkeleton>
  <scroll-view
    v-else
    class="viewport"
    scroll-y
    enable-flex
    lower-threshold="10"
    @scrolltolower="onScrollToLower"
  >
    <view class="top" v-if="profile">
      <block v-if="cartList?.length">
        <view class="item" v-for="item in cartList" :key="item.id">
          <!-- 选中状态 -->
          <uni-swipe-action>
            <uni-swipe-action-item :right-options="options" @click="deleteCart(item.skuId)">
              <navigator class="inner" :url="`/pages/goods/goods?id=${item.id}`" hover-class="none">
                <text
                  class="checkbox"
                  :class="{ checked: item.selected }"
                  @tap.stop="onChangeSelect(item)"
                ></text>
                <view class="pic-box">
                  <image class="pic" :src="item.picture" mode="aspectFill"></image>
                </view>
                <view class="meta">
                  <view class="name">{{ item.name }}</view>
                  <text class="attrs">{{ item.attrsText }}</text>
                  <view class="price">{{ (item.price * item.count).toFixed(2) }}</view>
                </view>
                <view class="count">
                  <vk-data-input-number-box
                    v-model="item.count"
                    :min="1"
                    :max="item.stock"
                    :index="item.skuId"
                    @change="onChangeCount"
                  ></vk-data-input-number-box>
                </view>
              </navigator>
            </uni-swipe-action-item>
          </uni-swipe-action>
        </view>
      </block>
      <view class="no-goods" v-else>购物车暂无商品，赶紧去购物吧！</view>
    </view>
    <view class="top-2" visited="" v-else>
      <view class="tip">登录后可查看购物车中的商品</view>
      <navigator class="to-login" url="/pages/login/login">去登录</navigator>
    </view>
    <view class="bottom">
      <XtxGuess style="display: flex; flex: 1" ref="xtxguessRef"></XtxGuess>
    </view>
    <view class="above" v-if="profile">
      <view class="left">
        <view class="all"
          ><text class="checkbox" :class="{ checked: selectAll }" @tap="onChangeAll">
            全选</text
          ></view
        >
        <view class="total"
          >合计: <text class="price">{{ totalPrice }}</text></view
        >
      </view>

      <view class="right">
        <button @tap="toPre" class="pay-btn" :style="{ opacity: selectedLength === 0 ? 0.5 : 1 }">
          去结算({{ selectedLength }})
        </button>
      </view>
    </view>
  </scroll-view>
</template>

<style lang="scss" scoped>
@import '../styles/CartMain.scss';
</style>
